<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="115px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="基础信息" name="item">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="工单编号">
                <el-input disabled value="使用系统编号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制单日期" prop="orderTime">
                <el-date-picker
                  v-model="formData.orderTime"
                  type="date"
                  value-format="x"
                  placeholder="选择"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="销售单号" prop="saleOrderNo">
                <el-input v-model="formData.saleOrderNo" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称" prop="customerName">
                <el-input disabled v-model="formData.customerName" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户编号" prop="customerCode">
                <el-input disabled v-model="formData.customerCode" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户交期" prop="customerDelivery">
                <el-input disabled v-model="formData.customerDelivery" class="!w-1/1" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产类型" prop="productionType">
                <el-select v-model="formData.productionType" placeholder="请选择">
                  <el-option label="销售推单" value="sales" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="部门" prop="departmentId">
                <el-select v-model="formData.departmentId" placeholder="请选择部门">
                  <el-option
                    v-for="dept in departmentList"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目" prop="projectId">
                <el-input disabled v-model="formData.projectId" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目阶段" prop="projectStage">
                <el-select v-model="formData.projectStage" placeholder="请选择">
                  <el-option label="设计" value="design" />
                  <el-option label="生产" value="production" />
                  <el-option label="验收" value="acceptance" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="目标客户" prop="targetCustomer">
                <el-input v-model="formData.targetCustomer" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="机台号" prop="machineNumber">
                <el-input v-model="formData.machineNumber" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备货客户" prop="stockingCustomer">
                <el-input v-model="formData.stockingCustomer" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="交货日期" prop="deliveryDate">
                <el-date-picker
                  v-model="formData.deliveryDate"
                  type="date"
                  placeholder="请选择"
                  class="!w-1/1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计划开始">
                <el-date-picker
                  v-model="formData.planBeginTime"
                  type="date"
                  placeholder="请选择"
                  class="!w-1/1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计划结束">
                <el-date-picker
                  v-model="formData.planEndTime"
                  type="date"
                  placeholder="请选择"
                  class="!w-1/1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="紧急程度" prop="urgencyLevel">
                <el-select v-model="formData.urgencyLevel" placeholder="请选择">
                  <el-option label="普通" value="normal" />
                  <el-option label="紧急" value="urgent" />
                  <el-option label="特急" value="emergency" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="负责人" prop="leader">
                <el-select v-model="formData.leader" placeholder="请选择" class="!w-1/1">
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.nickname"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户订单编号" prop="customerOrderNo">
                <el-input v-model="formData.customerOrderNo" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否有工序外协" prop="hasOutsourcing">
                <el-input v-model="formData.hasOutsourcing" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售订单备注" prop="salesRemark">
                <el-input type="textarea" v-model="formData.salesRemark" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="formData.remark"
                  placeholder="请输入"
                  :maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="版本号" prop="version">
                <el-input v-model="formData.version" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户订单编号" prop="cusOrderCode">
                <el-input v-model="formData.cusOrderCode" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="附件">
                <UploadFile :is-show-tip="false" v-model="formData.attachments" :limit="5" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
                 <el-form-item label="设计图" prop="images">
              <el-upload
                v-model:file-list="imageList"
                class="upload-image"
                action=""
                list-type="picture-card"
                multiple
                :auto-upload="false"
                :on-change="handleImageChange"
              >
                <el-icon><Plus /></el-icon>
                <template #file="{ file }">
                  <div class="image-item">
                    <img :src="file.url" alt="" class="image-preview" />
                    <span class="image-actions">
                      <span class="image-delete" @click="handleImageRemove(file)">
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="产品信息" name="item">
          <ProductList ref="itemFormRef" :items="formData.items"  />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import SaleOrderItemForm from './components/SaleOrderItemForm.vue'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import * as UserApi from '@/api/system/user'
import type { UploadFile } from 'element-plus'
import ProductList from '../../sale/quotationmanagement/components/productList.vue'
/** ERP 生产工单表单 */
defineOptions({ name: 'WorkOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  customerId: undefined,
  accountId: undefined,
  saleUserId: undefined,
  orderTime: undefined,
  remark: undefined,
  fileUrl: '',
  discountPercent: 0,
  discountPrice: 0,
  totalPrice: 0,
  depositPrice: 0,
  items: [],
  no: undefined // 订单单号，后端返回
})
const salesType = ref('1')
const formRules = reactive({
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  orderTime: [{ required: true, message: '订单时间不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表
const accountList = ref<AccountVO[]>([]) // 账户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    const totalPrice = val.items.reduce((prev, curr) => prev + curr.totalPrice, 0)
    const discountPrice =
      val.discountPercent != null ? erpPriceMultiply(totalPrice, val.discountPercent / 100.0) : 0
    formData.value.discountPrice = discountPrice
    formData.value.totalPrice = totalPrice - discountPrice
  },
  { deep: true }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) +'生产工单'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // formData.value = await SaleOrderApi.getSaleOrder(id)
    } finally {
      formLoading.value = false
    }
  }
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 100
  })
  // 加载客户列表
  customerList.value = (await CustomerApi.getCustomerPage(queryParams)).list
  // 加载用户列表
  // userList.value = await UserApi.getSimpleUserList()
  // 加载账户列表
  // accountList.value = await AccountApi.getAccountSimpleList()
  const defaultAccount = accountList.value.find((item) => item.defaultStatus)
  if (defaultAccount) {
    formData.value.accountId = defaultAccount.id
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const imageList = ref<UploadFile[]>([])
const handleImageRemove = (file: UploadFile) => {
  const index = imageList.value.findIndex((f) => f.uid === file.uid)
  if (index !== -1) {
    imageList.value.splice(index, 1)
    // 同时从formData中移除
    const imageIndex = formData.value.images.findIndex((f) => f.name === file.name)
    if (imageIndex !== -1) {
      formData.value.images.splice(imageIndex, 1)
    }
    // 释放对象URL
    if (file.url) {
      URL.revokeObjectURL(file.url)
    }
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SaleOrderVO
    if (formType.value === 'create') {
      // await SaleOrderApi.createSaleOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      // await SaleOrderApi.updateSaleOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    accountId: undefined,
    saleUserId: undefined,
    orderTime: undefined,
    remark: undefined,
    fileUrl: undefined,
    discountPercent: 0,
    discountPrice: 0,
    totalPrice: 0,
    depositPrice: 0,
    items: []
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>

.upload-file,
.upload-image {
  width: 100%;
}

.upload-image :deep(.el-upload) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.image-item {
  position: relative;

  /* width: 100px;
  height: 100px; */
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  right: 0;
  bottom: 0;
  display: flex;
  width: 100%;
  padding: 0 5px;
  background: rgb(0 0 0 / 50%);
  box-sizing: border-box;
  justify-content: flex-end;
}

.image-delete {
  padding: 5px;
  color: #fff;
  cursor: pointer;
}

.image-delete:hover {
  color: #ff4d4f;
}
</style>
